package cn.hamster3.mc.plugin.ball.bungee.listener;

import cn.hamster3.mc.plugin.ball.bungee.util.BallBungeeCordUtils;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.ball.common.entity.BallPlayerInfo;
import cn.hamster3.mc.plugin.ball.common.event.BallActions;
import cn.hamster3.mc.plugin.ball.common.event.player.BallPlayerLoginEvent;
import cn.hamster3.mc.plugin.ball.common.event.player.BallPlayerPostLoginEvent;
import cn.hamster3.mc.plugin.ball.common.event.player.BallPlayerPreLoginEvent;
import net.md_5.bungee.api.connection.PendingConnection;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.LoginEvent;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.event.PreLoginEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.event.EventPriority;

public final class BallBungeeMainListener implements Listener {
    public static final BallBungeeMainListener INSTANCE = new BallBungeeMainListener();

    private BallBungeeMainListener() {
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onPreLogin(PreLoginEvent event) {
        BallAPI.getInstance().sendRawBallMessage(
                BallAPI.BALL_CHANNEL,
                BallActions.BallPlayerPreLogin.name(),
                new BallPlayerPreLoginEvent(event.getConnection().getName())
        );
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onLogin(LoginEvent event) {
        if (event.isCancelled()) {
            return;
        }
        PendingConnection connection = event.getConnection();
        BallAPI.getInstance().sendRawBallMessage(
                BallAPI.BALL_CHANNEL,
                BallActions.BallPlayerLogin.name(),
                new BallPlayerLoginEvent(new BallPlayerInfo(
                        connection.getUniqueId(), connection.getName(), "connecting",
                        BallAPI.getInstance().getLocalServerId(), true
                ))
        );
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onPostLogin(PostLoginEvent event) {
        ProxiedPlayer player = event.getPlayer();
        BallPlayerInfo playerInfo = BallBungeeCordUtils.getPlayerInfo(player, true);
        BallAPI.getInstance().sendRawBallMessage(
                BallAPI.BALL_CHANNEL,
                BallActions.BallPlayerPostLogin.name(),
                new BallPlayerPostLoginEvent(playerInfo)
        );
    }
}
